package it.trekker.activities;

import java.io.File;
import java.io.IOException;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import it.trekker.R;
import it.trekker.camera.UtilityCamera;
import it.trekker.db.ExcursionCoordinate;
import it.trekker.db.GPSCoordinate;
import it.trekker.db.ExcursionCoordinateDAO;
import it.trekker.db.Photo;
import it.trekker.db.PhotoDAO;
import it.trekker.map.PathOverlayManager;
import it.trekker.map.PhotoItemizedOverlay;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class ExcursionMapActivity extends MapActivity {

	private static final String TAG = ExcursionMapActivity.class.getSimpleName();
	private MapView mapView = null;
	private ImageButton addPoi_bt = null;
	private MapController mapController = null;
	private int excursionId;

	//	private PathOverlayManager pathOverlayManager = null;
	//	private PhotoItemizedOverlay photoItemizedOverlay = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.map_layout);

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		
		addPoi_bt = (ImageButton) findViewById(R.id.add_poi);
		addPoi_bt.setVisibility(View.GONE);

		Bundle params = getIntent().getExtras();
		excursionId = params.getInt("excursion_id");

		mapController = mapView.getController();
		List<Overlay> mapOverlays = mapView.getOverlays();

		PathOverlayManager pathOverlayManager = new PathOverlayManager(this, mapOverlays, mapView.getProjection());
		drawPath(pathOverlayManager);

		Drawable marker = this.getResources().getDrawable(R.drawable.camera_icon);
		//		PhotoItemizedOverlay photoItemizedOverlay = new PhotoItemizedOverlay(marker, PhotoItemizedOverlay.CENTER, this);
		PhotoItemizedOverlay photoItemizedOverlay = new PhotoItemizedOverlay(this, mapView , marker);
		mapOverlays.add(photoItemizedOverlay);

		insertPhotoPoints(photoItemizedOverlay);
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}





	//*************************************************************//
	//********************* Utility functions *********************//
	//*************************************************************//

	private void drawPath(PathOverlayManager pathOverlayManager) {

		ExcursionCoordinateDAO gpsCoordinateDAO = new ExcursionCoordinateDAO(this);
		gpsCoordinateDAO.open();
		List<ExcursionCoordinate> coordinates = gpsCoordinateDAO.getAllCoordinatesByExcursion(excursionId);
		gpsCoordinateDAO.close();

		if(coordinates.size() > 0) {
			for(ExcursionCoordinate coord : coordinates) {
				pathOverlayManager.addPoint(GPSCoordinate.gpsCoordinate2GeoPoint(coord.getCoordinate()));
			}
			pathOverlayManager.endPath();

			// Move to first point if exist
			mapController.animateTo(GPSCoordinate.gpsCoordinate2GeoPoint(coordinates.get(0).getCoordinate()));
		}
		else {
			String message = getString(R.string.no_gpspoints);
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
		}
	}


	private void insertPhotoPoints(PhotoItemizedOverlay photoItemizedOverlay) {
		PhotoDAO photoDAO = new PhotoDAO(this);
		photoDAO.open();
		List<Photo> photos = photoDAO.getAllPhotosByExcursion(excursionId);
		photoDAO.close();

		for(Photo photo : photos) {
			if(new File(photo.getPath()).exists()) {
				try {

					ExifInterface exif = new ExifInterface(photo.getPath());
					String dateStr = exif.getAttribute(ExifInterface.TAG_DATETIME);
					String latitudeStr = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
					String latitudeRefStr = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
					String longitudeStr = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
					String longitudeRefStr = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

					double latitude = UtilityCamera.dms2decimal(latitudeStr, latitudeRefStr, UtilityCamera.LATITUDE);
					double longitude = UtilityCamera.dms2decimal(longitudeStr, longitudeRefStr, UtilityCamera.LONGITUDE);
					GeoPoint p = GPSCoordinate.gpsCoordinate2GeoPoint(latitude, longitude);
					photoItemizedOverlay.addItem(p, dateStr, photo.getPath());

					// TODO Cercare di far caricare le foto con i dati dal db
					
//					double latitude = photo.getLatitude();
//					double longitude = photo.getLongitude();
//					GeoPoint p = GPSCoordinate.gpsCoordinate2GeoPoint(latitude, longitude);
//					photoItemizedOverlay.addItem(p, dateStr, photo.getPath());
					
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
	}


	private String formatTimestamp(String timestamp) {

		String[] splitted = timestamp.split(" ");
		String[] date = splitted[0].split(":");
		String time = splitted[1];

		String year = date[0];
		String month = date[1];
		String day = date[2];

		return String.format("%s/%s/%s %s", day, month, year, time);
	}





	//***********************************************************//
	//*********************** Option Menu ***********************//
	//***********************************************************//


	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.map_menu, menu);

		return true;
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		case R.id.map_mode_view:
			if(!mapView.isSatellite())
				mapView.setSatellite(true);
			else {
				mapView.setSatellite(false);
			}
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
